/**
 * author:Administrator
 * date:2015/7/27
 * desc:TODO
 */

'use strict';
var debugLog = require('../../function.js').debugLog;
let esClient = require('./elasticSearch.js');
let metaInfo = require('./model/article.js');
let BaseEsDao = require('./BaseEsDao.js');
let util = require('util');

var filterChain = require('./filter/ChainFilter.js').defaultFilterChain(false);

function ElasticDao() {
  this.init(metaInfo, esClient);
}
util.inherits(ElasticDao, BaseEsDao);

module.exports = new ElasticDao();

let theProto = ElasticDao.prototype;
/**
 * 机器匹配
 *
 {
    ctype: 0用户分类,1人工,2机器,
    content: xxx,
    top: 4
 }


 {
     "query":{
         "filtered" : {
             "query" : {"match": {"articleContent":"blabla"}},
             "filter" : {
                 "bool": {
                     "must":[
                         {"term":{"status":1}},
                         {"or" : [
                             { "term" : { "ctype" : 0 }},
                             { "term" : { "ctype" : 1 }}
                         ]}
                     ]
                 }
             }
         }
     }
 }
 * @param json
 * @returns {*}
 */
theProto.autoCate = function*(json) {
  let self = this;
  var body = {
    "query": {
      "filtered": {
        "query": {
          "match": {"articleContent": json.text}
        },
        "filter": {
          "bool": {
            "must": [
              {"term": {"status": 1}},
              {"term": {"ctype": json.ctype}}
            ]
          }
        }
      }
    }
  };

  //console.log('auto cate:', JSON.stringify(body));

  let res = yield this.client.search({
    index: self.index,
    type: self.type,
    from: 0,
    size: json.top,
    body: body
  });

  return res.hits;
};


/**
 * 自定义打分 * 拼凑一个 json,发请求
 * @param json {q:"xx",add: 1, sub: 2, mul: 3}
 */
let urlCScore = 'http://host/index/type/_search';
theProto.cScore = function*(json) {
  let body = {
    "query": {
      "filtered": {
        "filter": {
          "bool": {
            "must": {
              "term": {"articleContent": json.q}
            }
          }
        },

        "query": {
          "function_score": {
            "boost_mode": "replace",
            "functions": [
              {
                "script_score": {
                  "params": {"f_add": json.add, "f_sub": json.sub, "f_mul": json.mul},
                  "script": "doc['uid'].value*f_mul + f_add - f_sub"
                }
              }
            ]
          }
        }
      }
    }
  };
  let url = urlCScore.replace('host', this.host);
  url = url.replace('index', this.index);
  url = url.replace('type', this.type);
  let result = yield this.requestPost(url, body);

  return result;
};


/**
 * {q: q, size: size, from: from}
 * search a long text
 POST o2o/article/_search?_source=articleContent
 {
   "from" : 0,
   "size" : 100,
   "query": {
     "match": { "articleContent": "long"}
   }
 }
 * @param json
 */
theProto.qSearchLong = function*(json) {
  debugLog('qSearchLong', json);
  let url = urlSearchLong.replace('host', this.host);
  url = url.replace('index', this.index);
  url = url.replace('type', this.type);
  var body = {
    "from": json.from,
    "size": json.size,
    "query": {
      "match": {"articleContent": json.q}
    }
  };
  let result = yield this.requestPost(url, body);
  return result.hits;
};
let urlSearchLong = 'http://host/index/type/_search?_source=articleContent';

/**
 * 使用ik_smart进行分析，返回词频
 * @param text
 */
theProto.analyze = function*(text) {
  let self = this;
  let params = {
    analyzer: 'ik_smart',
    index: self.index,
    text: text
  };
  let res = yield this.client.indices.analyze(params);
  let ret1 = res.tokens.map(function (item) {
    return item.token;
  });

  //let ret2 = [];
  //ret1.forEach(word => {
  // if( filterChain.doFilte(word)) ret2.push(word);
  //});
  return ret1;
};

//replies:n,             Default: 3：n条或以上回复；0 不过滤此项
//disableVest:n,     Default: 0：1 只返回用户贴；0 不过滤此项，包含马甲贴
//imgcount:n          Default: 1：1 必须包含图片; 0 不检查是否包含图片
//views:n                Default: 5： 查看次数n次或以上；0 不检测查看次数
theProto.fineSearch = function*(json) {
  var self = this;

  var body = {
    "query": {
      "filtered": {
        "query": {
          "match": {"articleContent": json.text}
        },
        "filter": {
          "bool": {
            "must": [
              {"term": {"status": 1}}
            ]
          }
        }
      }
    }
  };

  if (json.replies) {
    body.query.filtered.filter.bool.must.push({"range": {"replies": {"gte": json.replies}}});
    //body.query.filtered.filter.bool.must.push({"numeric_range": {"replies": {"gte": json.replies}}});
  }
  if (json.imgcount) {
    body.query.filtered.filter.bool.must.push({"range": {"imgcount": {"gte": json.imgcount}}});
    //body.query.filtered.filter.bool.must.push({"numeric_range": {"imgcount": {"gte": json.imgcount}}});
  }
  if (json.views) {
    body.query.filtered.filter.bool.must.push({"range": {"views": {"gte": json.views}}});
    //body.query.filtered.filter.bool.must.push({"numeric_range": {"views": {"gte": json.views}}});
  }
  if (json.disableVest) {
    body.query.filtered.filter.bool.must.push({"term": {"vest": 0}});
  }

  debugLog('fineSearch:', JSON.stringify(body));
  let opt = {
    index: self.index,
    type: self.type,
    from: 0,
    size: json.size || 10,
    body: body
  };
  if (json.fields) {
    opt._sourceInclude = json.fields;
  }
  let res = yield this.client.search(opt);
  return res.hits;
};